import React, { Component } from 'react';
import { DatePicker, Table, Icon, Popover, Button, Spin } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { CONST_DATE_FORMAT } from '@/constants';
import { getCookie } from '@/utils/utils';
import styles from '../index.less';

import List from '@/pages/Staff';

export default class Index extends Component {
  constructor(props) {
    super(props);
    const { selectedData = {}, selectedTime } = props;
    this.state = {
      constants: {},
      data: { ...selectedData },
      time: selectedTime,
    };
    this.refresh = false;
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'title/queryData',
      payload: {
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, titles: data } });
        },
      },
    });
    this.props.dispatch({
      type: 'shift/queryData',
      payload: {
        current: 1,
        pageSize: 10000,
        callback: (data = []) => {
          this.setState({ constants: { ...this.state.constants, shifts: data } });
        },
      },
    });
  }

  componentWillUnmount() {
    if (this.refresh) {
      const { dispatch, modularName, selectedTime } = this.props;
      const { time } = this.state;

      if (selectedTime && time && selectedTime.format('YYYY-MM') === time.format('YYYY-MM')) {
        dispatch({
          type: `${modularName}/changeState`,
          payload: {
            refreshTime: new Date().valueOf(),
          },
        });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !_.isEqual(this.props, nextProps) || !_.isEqual(this.state, nextState);
  }

  generateColumns = (titles, data = {}, allowEdit) => {
    const columns = [
      {
        title: '',
        dataIndex: 'shift_type',
        ellipsis: true,
        render: (text, record) => {
          const { shift_name, start_date, end_date } = record;

          return (
            <div style={{ color: 'rgb(43, 151, 239)', textAlign: 'center' }}>
              <div>{shift_name}</div>
              <div>{`${start_date}~${start_date < end_date ? `` : `次日`}${end_date}`}</div>
            </div>
          );
        },
      },
    ];

    if (titles && titles.length > 0) {
      titles.forEach(item => {
        columns.push({
          title: item.title_name,
          dataIndex: item.id,
          align: 'center',
          ellipsis: true,
          render: (text, record) => {
            const arrange = data[record.id];
            const { children = [] } = arrange || {};

            const filter = children.filter(child => item.id === child.title_id);
            if (filter && filter[0]) {
              const { name, mobile } = filter[0];

              return (
                <div style={{ textAlign: 'center' }}>
                  <div>
                    {name}
                    {allowEdit && (
                      <Popover
                        content={
                          <div>
                            <div style={{ marginBottom: 16 }}>确定删除该数据?</div>
                            <div>
                              <Button
                                size="small"
                                type="primary"
                                onClick={this.deleteBtnClick.bind(this, filter[0])}
                              >
                                确定
                              </Button>
                            </div>
                          </div>
                        }
                        title={null}
                        trigger="hover"
                      >
                        <Icon
                          type="delete"
                          theme="twoTone"
                          style={{ cursor: 'pointer', marginLeft: 12 }}
                          onClick={e => e.stopPropagation()}
                        />
                      </Popover>
                    )}
                  </div>
                  <div>{mobile}</div>
                </div>
              );
            }
          },
          onCell: record => {
            return {
              onClick: allowEdit
                ? () => {
                    const { start_date, end_date } = record;
                    const arrange = data[record.id];
                    const { time } = this.state;
                    const { children = [] } = arrange || {};
                    let shift_user = undefined;
                    let mobile = undefined;

                    const filter = children.filter(child => item.id === child.title_id);
                    if (filter && filter[0]) {
                      shift_user = filter[0].user_id;
                      mobile = filter[0].mobile;
                    }
                    this.setState({
                      selectedCell: {
                        shift_date:
                          typeof time === 'object' ? time.format(CONST_DATE_FORMAT) : time,
                        shift_unit: this.props.currentUnit.id,
                        shift_id: record.id,
                        shift_title: item.id,
                        shift_user,
                        mobile,
                        period: `${start_date}~${start_date < end_date ? `` : `次日`}${end_date}`,
                      },
                    });
                  }
                : null,
            };
          },
        });
      });

      return columns;
    }

    return [
      ...columns,
      { title: '', dataIndex: 'empty_01' },
      { title: '', dataIndex: 'empty_02' },
      { title: '', dataIndex: 'empty_03' },
    ];
  };

  onChange = time => {
    this.setState({ time }, () => {
      this.queryData();
    });
  };

  saveOrUpdateBtnClick = (cell, data) => {
    const { dispatch, modularName } = this.props;
    const { shift_date, shift_id, shift_title, mobile, period } = cell || {};
    const { name, user_name, unitname } = data || {};
    const date = moment(shift_date, 'YYYY-MM-DD');
    const diff = date.diff(moment(), 'days');
    let dates = [];

    if (diff <= 0) {
      dates = [moment().format('YYYY-MM-DD HH:mm:ss')];
    } else if (diff >= 1 && diff < 3) {
      dates = [
        date
          .clone()
          .add(-1, 'days')
          .format('YYYY-MM-DD 08:30:00'),
      ];
    } else if (diff >= 3 && diff < 7) {
      dates = [
        date
          .clone()
          .add(-1, 'days')
          .format('YYYY-MM-DD 08:30:00'),
        date
          .clone()
          .add(-3, 'days')
          .format('YYYY-MM-DD 08:30:00'),
      ];
    } else if (diff >= 7) {
      dates = [
        date
          .clone()
          .add(-1, 'days')
          .format('YYYY-MM-DD 08:30:00'),
        date
          .clone()
          .add(-3, 'days')
          .format('YYYY-MM-DD 08:30:00'),
        date
          .clone()
          .add(-7, 'days')
          .format('YYYY-MM-DD 08:30:00'),
      ];
    }

    dispatch({
      type: `${modularName}/saveOrUpdateData`,
      payload: {
        cell,
        data,
        callback: () => {
          const list = dates.map(item => {
            return {
              smsContent: `温馨提示：你好，${name}同志，根据你单位的上报信息，${moment(
                shift_date,
                'YYYY-MM-DD',
              ).format('MM月DD日')}${period}轮到你值班，请认真做好值班工作！-${unitname}`,
              smsPhone: user_name,
              smsSendTime: item,
              userDept: '长宁区城市运行值守保障管理系统',
              userName: getCookie('displayName'),
              userRealName: getCookie('displayName'),
              smsType: `${shift_date}_${shift_id}_${shift_title}`,
              dutyDate: shift_date,
            };
          });
          if (cell.shift_user) {
            dispatch({
              type: `${modularName}/deleteSms`,
              payload: {
                data: {
                  dutyDate: shift_date,
                  smsPhone: mobile,
                  smsType: `${shift_date}_${shift_id}_${shift_title}`,
                },
              },
            });
          }
          dispatch({
            type: `${modularName}/sendSms`,
            payload: {
              data: list,
            },
          });

          this.setState({ selectedCell: {} });
          this.refresh = true;
          this.queryData();
        },
      },
    });
  };

  deleteBtnClick = (data, e) => {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    const { dispatch, modularName } = this.props;

    dispatch({
      type: `${modularName}/deleteData`,
      payload: {
        data: {
          shift_date: data.date,
          shift_unit: data.unit_id,
          shift_id: data.shift_id,
          shift_title: data.title_id,
        },
        callback: () => {
          dispatch({
            type: `${modularName}/deleteSms`,
            payload: {
              data: {
                dutyDate: data.date,
                smsPhone: data.mobile,
                smsType: `${data.date}_${data.shift_id}_${data.title_id}`,
              },
            },
          });

          this.refresh = true;
          this.queryData();
        },
      },
    });
  };

  queryData = () => {
    const { time } = this.state;
    const { dispatch, modularName, currentUnit = {} } = this.props;

    dispatch({
      type: `${modularName}/queryDataByDay`,
      payload: {
        shift_unit: { id: currentUnit.id },
        shift_date: typeof time === 'object' ? time.format(CONST_DATE_FORMAT) : time,
        callback: (data = {}) => {
          this.setState({ data });
        },
      },
    });
  };

  render() {
    const { constants = {}, data = {}, time, selectedCell = {} } = this.state;
    const { titles = [], shifts = [] } = constants;
    const { loading, modularName, allowEdit, currentUnit } = this.props;

    return (
      <Spin
        spinning={
          !!loading.effects[`${modularName}/queryDataByDay`] ||
          !!loading.effects[`${modularName}/saveOrUpdateData`] ||
          !!loading.effects[`${modularName}/deleteData`]
        }
      >
        <div style={{ minHeight: 608 }}>
          {_.isEmpty(selectedCell) ? (
            <>
              <div style={{ marginBottom: 16 }}>
                <DatePicker
                  allowClear={false}
                  style={{ width: 220 }}
                  value={time}
                  onChange={this.onChange}
                />
              </div>
              <div className={styles.table_wrapper}>
                <Table
                  bordered
                  columns={this.generateColumns(titles, data, allowEdit)}
                  dataSource={shifts}
                  loading={
                    !!loading.effects[`title/queryData`] || !!loading.effects[`shift/queryData`]
                  }
                  pagination={false}
                  rowKey="id"
                />
              </div>
            </>
          ) : (
            <List
              currentUnit={currentUnit}
              mode="select"
              style={{ backgroundColor: '#fff' }}
              tableOptions={{
                scroll: { x: 975, y: 560, scrollToFirstRowOnChange: true },
                onRow: record => {
                  return {
                    style: { cursor: 'pointer' },
                    onClick: () => {
                      this.saveOrUpdateBtnClick({ ...selectedCell }, record);
                    },
                  };
                },
              }}
              toolExtra={
                <Button icon="double-left" onClick={() => this.setState({ selectedCell: {} })}>
                  返回
                </Button>
              }
            />
          )}
        </div>
      </Spin>
    );
  }
}
